#!/bin/sh

# check args
    if ! [ $# -gt 0 ] ; then echo "require 4 args : src fn wrk prn" ; exit ; fi

src="$1"
    if ! [ -d "$src" ] ; then echo "source folder not exist: $src" ; exit ; fi

fn="$2"
    if ! [ -f "$src/$fn.pdf" ] ; then echo "pdf file not exist: $fn.pdf" ; exit ; fi
    echo "  $fn"

wrk="$3"
    if ! [ -d "$wrk" ] ; then echo "work folder not exist: $wrk" ; exit ; fi

printer="$4"
    lpq -P "$printer" 2>/dev/null 1>/dev/null
    if ! [ $? -eq 0 ] ; then echo "printer not exist: $printer" ; exit ; fi

# pdf --> ps
    ps_opt="-start 1 -end 1 -level3 -size a4 -shrink -rotateAndCenter"
    acroread -toPostScript $ps_opt "$src/$fn.pdf" "$wrk"
    chmod g+rw "$wrk/$fn.ps"

# ps --> alt.ps
    ps_alt="ps_alt.pl"
        ps_alt=$( echo $0 | perl -pe ' s,[^/]*$,'$ps_alt', ' )
    perl "$ps_alt" "$fn" "$wrk/$fn.ps" "$wrk/$fn.alt.ps"
    chmod g+rw "$wrk/$fn.alt.ps"

# alt.ps --> printer
    lpr -P "$printer" -l "$wrk/$fn.alt.ps"

# ps , alt.ps --> remove
    rm "$wrk/$fn.ps" "$wrk/$fn.alt.ps"

